package com.mk.cloud.pt.controller;

import act.job.Cron;
import act.job.Every;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.mk.cloud.common.domain.PBalanceTime;
import com.mk.cloud.common.domain.PCompany;
import com.mk.cloud.common.domain.PUser;
import com.mk.cloud.common.enums.ConfigCode;
import com.mk.cloud.common.enums.GlobalValues;
import com.mk.cloud.common.interceptor.ITransacte;
import com.mk.cloud.common.util.DateUtils;
import com.mk.cloud.pt.service.app.RewardService;
import org.osgl.mvc.annotation.With;
import org.osgl.util.S;

import javax.inject.Inject;
import java.math.BigDecimal;
import java.util.*;

public class TimeTaskController {

    @Inject
    private PUser.Mapper pUserMapper;
    @Inject
    private PCompany.Mapper pCompanyMapper;
    @Inject
    private PBalanceTime.Mapper pBalanceTimeMapper;
    @Inject
    private RewardService rewardService;

    private Map<String,Map<Integer,BigDecimal>> map;

    //初始时间
    private final String finalbegintime = "2018-06-05 00:00:00";
//    private final String finalbegintime = "2018-01-05 00:00:00";

//    private final int balanceTimeSpan = 137;//时间间隔
    private final int balanceTimeSpan = 180;//时间间隔

    /**
     * 发放PK奖励
     * 开始时间固定为6月1日
     */
    @With(ITransacte.class)
    @Cron("0 0 0 * * *")
//    @Every("60s")
    public void sendPKReward(){
        String begintime = pBalanceTimeMapper.queryLast();
        if(S.isBlank(begintime)){
            begintime = finalbegintime;
        }
        String endtime = DateUtils.getTimeNow();
        System.out.println(DateUtils.addSecond(begintime,balanceTimeSpan*24*60*60));
        if(DateUtils.compareDate(DateUtils.addSecond(begintime,balanceTimeSpan*24*60*60),endtime)){
            return;
        }
        List<PCompany> companys = pCompanyMapper.all();
        JSONObject resjson = new JSONObject();
        for (PCompany company : companys){
            List<Integer> ratios = getMinRatio(company.getCoid());
            //统计每个品牌区域达到基本资格的人,并倒序排好
            List<JSONObject> ratioList = pUserMapper.countRatioUser(ratios.get(ratios.size()-1)+"",company.getCoid(),begintime,endtime);
            System.out.println(JSON.toJSONString(ratioList));
            if(ratioList!=null&&ratioList.size()>0){
                for (JSONObject json: ratioList) {
                    JSONObject prejson = resjson.getJSONObject(json.getString("taid"));
                    if(prejson==null){
                        //判断该用户应得到那种层次的pk奖励
                        for(Integer ratio :ratios){
                            if(json.getBigDecimal("ratio").compareTo(new BigDecimal(ratio))>=0){
                                /**
                                 * taidvalue:
                                 * {
                                 * "ratio":ratio,
                                 * "realratio":realratio,
                                 *  "basereward":reward
                                 *  "list" : [
                                 *      {
                                 *          "fuserid":fuserid
                                 *      }
                                 *  ],
                                 * }
                                 */
                                JSONObject obj = new JSONObject();
                                obj.put("ratio",ratio);
                                obj.put("realratio",json.getBigDecimal("ratio"));//实际统计结果
                                obj.put("basereward",map.get(company.getCoid()).get(ratio));
                                JSONArray arr = new JSONArray();
                                arr.add(json);
                                obj.put("list",arr);
                                resjson.put(json.getString("taid"),obj);
                                System.out.println(resjson);
                                break;
                            }
                        }
                    }else{
                        //判断该用户是否与之前同一区域的用户的推广数量相同,相同则评分奖励
                        if(json.getBigDecimal("ratio").compareTo(prejson.getBigDecimal("realratio"))==0){
                            prejson.getJSONArray("list").add(json);
                        }
                    }
                }
            }
        }
        //发放奖励
        for(String str : resjson.keySet()){
            JSONObject json = resjson.getJSONObject(str);
            JSONArray arr = json.getJSONArray("list");
            JSONObject j = arr.getJSONObject(0);
            int baseNum = j.getIntValue("counttaid");
            //多人拓店数相同,则平分奖励
            BigDecimal allmoney = json.getBigDecimal("basereward").multiply(new BigDecimal(baseNum)).divide(new BigDecimal(arr.size()),2,BigDecimal.ROUND_DOWN);//pk奖励总金额'
            for(Object obj:arr){
                JSONObject jsonObj = (JSONObject)obj;
                PUser user = new PUser();
                user.setFuserid(jsonObj.getString("fuserid"));
                user.setCoid(jsonObj.getString("coid"));
                pUserMapper.addWalletByFuserid(user.getPfuserid(),allmoney);
                PUser pUser = pUserMapper.single(user.getFuserid());
                BigDecimal balance = pUser.getWalletamount().subtract(pUser.getLockamount());
                rewardService.addFlow(user,user.getFuserid(), GlobalValues.FLOW_TYPE_0.value(),allmoney,balance,GlobalValues.SOURCETYPE_2.value(),"PK胜出奖励,区域同期得奖人数:"+arr.size()+"人");
            }
        }

        pUserMapper.updatePkedToOne(begintime,endtime);
        //插入下次的开始时间
        PBalanceTime pBalanceTime = new PBalanceTime();
        pBalanceTime.setBegintime(endtime);
        pBalanceTimeMapper.insert(pBalanceTime);

    }

    public List<Integer> getMinRatio(String coid){
        JSONArray array = JSON.parseArray(ConfigCode.valueOf("FISSION_PK_REWARD").value(coid));
        List<Integer> list = new ArrayList<>();
        map = new HashMap<>();
        Map<Integer,BigDecimal> innerMap = new HashMap<>();
        for(Object obj:array){
            JSONArray arr = (JSONArray) obj;
            list.add(arr.getInteger(0));
//            min = Integer.min(min,arr.getInteger(0));
            innerMap.put(arr.getInteger(0),arr.getBigDecimal(1));
        }
        map.put(coid,innerMap);
        Collections.sort(list);
        Collections.reverse(list);
        return list;
    }
}
